//
//  TTXML.m
//  Tint
//
//  Created by Kevin Wu on 4/19/12.
//  Copyright (c) 2012 Telligenty. All rights reserved.
//

#import "TTXML.h"

@implementation TTXML


#pragma mark - Memory

- (id)initWithXMLString:(NSString *)string {
    return [self initWithXMLData:[string dataUsingEncoding:NSUTF8StringEncoding]];
}

- (id)initWithXMLData:(NSData *)data {
    self = [super init];
    if (self) {
        _XMLDocument = xmlReadMemory((const char*)[data bytes], (int)[data length], NULL, NULL, XML_PARSE_NOCDATA | XML_PARSE_NOBLANKS);
    }
    return self;
}

- (id)initWithRootName:(NSString *)name {
    self = [super init];
    if (self) {
        _XMLDocument = xmlNewDoc((const xmlChar*)"1.0");
        if (_XMLDocument != NULL) {
            xmlNodePtr node = xmlNewNode(NULL, (const xmlChar *)[name UTF8String]);
            xmlDocSetRootElement(_XMLDocument, node);
        }
    }
    return self;
}

- (void)dealloc {
    if (_XMLDocument != NULL) {
        xmlFreeDoc(_XMLDocument);
    }
    [super dealloc];
}


#pragma mark - Public

+ (TTXML *)XMLWithXMLString:(NSString *)string {
    return [[[self alloc] initWithXMLString:string] autorelease];
}

+ (TTXML *)XMLWithXMLData:(NSData *)data {
    return [[[self alloc] initWithXMLData:data] autorelease];
}

+ (TTXML *)XMLWithRootName:(NSString *)name {
    return [[[self alloc] initWithRootName:name] autorelease];
}


- (TTXMLNode *)rootElement {
    if (_XMLDocument != NULL) {
        xmlNodePtr rootNode = xmlDocGetRootElement(_XMLDocument);
        if (rootNode) {
            return [TTXMLNode nodeWithXMLNode:rootNode];
        }
    }
    return nil;
}


- (NSData *)XMLData {
    if (_XMLDocument != NULL) {
        
        xmlChar *buffer = NULL;
        int bufferSize = 0;
        
        xmlDocDumpMemory(_XMLDocument, &buffer, &bufferSize);
        
        if (buffer) {
            NSData *data = [NSData dataWithBytes:buffer length:bufferSize];
            xmlFree(buffer);
            return data;
        }
    }
    return nil;
}

@end
